package com.ruoyi.quartz.task;

import com.ruoyi.quartz.domain.UnreadEmailArchive;
import com.ruoyi.quartz.mapper.UnreadEmailArchiveMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
import java.util.Date;
import java.util.Properties;
import java.util.stream.Collectors;
import java.sql.Timestamp;

/**
 * 定时任务调度 —— 自动获取业务员的邮件，并存储到数据库表 `unread_email_archive`（通过 MyBatis Mapper）
 */
@Component("custMail")
public class CustMail {

    @Autowired
    private UnreadEmailArchiveMapper unreadEmailArchiveMapper;

    public void custMailFromServer() {
        // —— 配置你的邮箱服务器信息 ——
        String host     = "imap.exmail.qq.com";
        int    port     = 993;
        String username = "import@lanyachem.com";
        String password = "sGrgFCcht8vTmMVe";

        // 1. 设置 JavaMail 连接属性
        Properties props = new Properties();
        props.put("mail.store.protocol", "imaps");
        props.put("mail.imaps.host", host);
        props.put("mail.imaps.port", String.valueOf(port));
        props.put("mail.imaps.ssl.enable", "true");

        Session session = Session.getInstance(props);
        try (Store store = session.getStore("imaps")) {
            // 2. 连接到 IMAP 服务器
            store.connect(host, port, username, password);

            // 3. 打开 INBOX（读写模式）
            try (Folder inbox = store.getFolder("INBOX")) {
                inbox.open(Folder.READ_WRITE);

                // 4. 搜索所有“未读”邮件
                Message[] msgs = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
                System.out.printf("共拉取到 %d 封未读邮件：%n", msgs.length);

                for (Message m : msgs) {
                    // 5. 提取邮件信息
                    String messageId = ((MimeMessage) m).getMessageID();
                    String from      = ((InternetAddress) m.getFrom()[0]).getAddress();
                    String toList    = m.getAllRecipients() != null
                            ? java.util.Arrays.stream(m.getAllRecipients())
                            .map(addr -> ((InternetAddress) addr).getAddress())
                            .collect(Collectors.joining(","))
                            : "";
                    String subject   = m.getSubject();
                    Date   sentDate  = m.getSentDate();
                    String body      = extractText(m);

                    // 6. 构建实体并调用 Mapper 存储
                    UnreadEmailArchive email = new UnreadEmailArchive();
                    email.setMessageId(messageId);
                    email.setFromAddress(from);
                    email.setToAddresses(toList);
                    email.setSubject(subject);
                    email.setBody(body);
                    email.setSentTime(new Timestamp(sentDate.getTime()));
                    email.setFetchDate(new Date());

                    unreadEmailArchiveMapper.insertUnreadEmailArchive(email);

                    // 7. 标记为已读
                    m.setFlag(Flag.SEEN, true);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String extractText(Part part) throws Exception {
        if (part.isMimeType("text/*")) {
            return (String) part.getContent();
        }
        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                String txt = extractText(mp.getBodyPart(i));
                if (txt != null && !txt.isEmpty()) {
                    return txt;
                }
            }
        }
        if (part.isMimeType("message/rfc822")) {
            return extractText((Part) part.getContent());
        }
        return "";
    }
}
